import string
class FSM:
    """利用状态机实现将简单加减乘除运算式子变成token
    
    如 ' 12 + 34 * 567 ' 转换成 ['12', '+', '34', '*', '456']
    """
    symbolNumber = '0123456789'
    symbolOperator = '+-/*'

    def __init__(self):
        self.token = []
        self.tokens = []
        self.EOF = -1
        self.blankFollowingNum = False
    
    def start(self, char: str):
        if char in self.symbolNumber:
            return self.nextNumber(char)
        elif char.isspace():
            return self.start
        else:
            return self.EOF
        
    
    def nextOperator(self, char: str):
        self.tokens.append(char)
        return self.nextNumber

    
    def nextNumber(self, char: str):
        if char in self.symbolNumber:
            if self.blankFollowingNum:
                return self.EOF
            self.token.append(char)
            return self.nextNumber
        elif char in self.symbolOperator:
            self.blankFollowingNum = False
            self.tokens.append(''.join(self.token))
            self.token.clear()
            return self.nextOperator(char)
        elif char.isspace():
            if len(self.token) != 0:
                self.blankFollowingNum = True
            return self.nextNumber
        else:
            return self.EOF
    
    def end(self):
        self.tokens.append(''.join(self.token))
        self.token.clear()

    
fsm = FSM()
expression = ' 12 + 34 * 567 '
state = fsm.start
for char in expression:
    state = state(char)
    if state == fsm.EOF:
        print('表达式不合法')
        break
fsm.end()
print('tokens:', fsm.tokens)